﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
using System.Drawing;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace mckfrpc
{
    public partial class frpc : Form
    {
        Process proc = new Process();
        Thread t = new Thread(()=> { });

        public frpc()
        {
            InitializeComponent();
            // 在这里处理输出结果，例如显示在文本框中
            StartCmd();
        }

        private void StartCmd()
        {
            try
            {
                 t = new Thread(() =>
                {
                    proc.StartInfo.FileName = mck.frpc.Program.frpName;
                    //proc.StartInfo.Arguments = string.Format("10");//this is argument
                    proc.StartInfo.UseShellExecute = false;
                    proc.StartInfo.RedirectStandardInput = true; //标准输入
                    proc.StartInfo.RedirectStandardOutput = true; //标准输出
                    proc.StartInfo.CreateNoWindow = true;
                    proc.Start();
                    proc.OutputDataReceived += new DataReceivedEventHandler(OutputHandler);
                    proc.BeginOutputReadLine();
                    proc.WaitForExit();
                    proc.Close();

                });
                t.IsBackground = true;
                t.Start();
            }
            catch (Exception ex)
            {
                this.txt_cmd.Text = string.Format("Exception Occurred :{0},{1}", ex.Message, ex.StackTrace.ToString());
                MessageBox.Show("出错了，请查看运行日志！");
            }
        }

        private void button1_Click(object sender, EventArgs e)
        {
            // var cmd = txt_cmd.Text.ToString().Trim(); // 这里可以替换为你想要执行的cmd命令
            // var process = new Process
            // {
            //     StartInfo = new ProcessStartInfo
            //     {
            //         FileName = "cmd.exe",
            //         RedirectStandardInput = true,
            //         RedirectStandardOutput = true,
            //         UseShellExecute = false,
            //         CreateNoWindow = true
            //     }
            // };

            // Thread t = new Thread(() =>
            // {
            //     process.Start();
            //     this.Invoke(
            //new Action(() =>
            // {
            //     this.lsitBox_cmd.Items.Add("已开始执行");
            //     this.lsitBox_cmd.SelectedIndex = lsitBox_cmd.Items.Count - 1;
            // }));
            //     using (var sw = process.StandardInput)
            //     {
            //         if (sw.BaseStream.CanWrite)
            //         {
            //             sw.WriteLine(cmd); // 写入命令
            //         }
            //     }

            //     // 获取命令执行结果
            //     var output = process.StandardOutput.ReadToEnd();
            //     process.WaitForExit(); // 等待程序执行完毕
            //     this.Invoke(
            // new Action(() =>
            // {
            //     var sli = output.Split(new string[] { "\r\n" }, StringSplitOptions.RemoveEmptyEntries);
            //     //txt_cmd.Text = output;
            //     foreach (string item in sli)
            //     {
            //         this.lsitBox_cmd.Items.Add(item);
            //         this.lsitBox_cmd.SelectedIndex = lsitBox_cmd.Items.Count - 1;
            //     }

            //     this.lsitBox_cmd.Items.Add("结束");
            //     this.lsitBox_cmd.SelectedIndex = lsitBox_cmd.Items.Count - 1;
            // }));

            // });
            // t.IsBackground = true;
            // t.Start();



            //// 在这里处理输出结果，例如显示在文本框中
            //this.lsitBox_cmd.Items.Add(output);
            //var sli = output.Split(new string[] { "\r\n" }, StringSplitOptions.RemoveEmptyEntries);
            ////txt_cmd.Text = output;
            //foreach(string item in sli)
            //{
            //    this.lsitBox_cmd.Items.Add(item);
            //    this.lsitBox_cmd.SelectedIndex = lsitBox_cmd.Items.Count - 1;
            //}
        }

        private void OutputHandler(object sender, DataReceivedEventArgs outLine)
        {
            if (!String.IsNullOrEmpty(outLine.Data))
            {
                string data = outLine.Data.ToString();
                byte[] bytes = Encoding.Default.GetBytes(data);
                data= System.Text.Encoding.GetEncoding("UTF-8").GetString(bytes);

                //Encoding sourceEncoding = Encoding.UTF8;
                //Encoding targetEncoding = Encoding.Unicode;

                //byte[] bytes = sourceEncoding.GetBytes(data);
                //data = targetEncoding.GetString(bytes);

                this.Invoke(
            new Action(() =>
            {
                this.lsitBox_cmd.Items.Add(data);
                this.lsitBox_cmd.SelectedIndex = lsitBox_cmd.Items.Count - 1;
            }));
            }
        }

        private void Form1_Load(object sender, EventArgs e)
        {

        }

        private void Form1_FormClosed(object sender, FormClosedEventArgs e)
        {
           // CloseProcess();
           // System.Environment.Exit(0);
        }

        /// <summary>
        /// 关闭所有线程
        /// </summary>
        private void CloseProcess()
        {

            // 假设我们要结束的进程名为"notepad.exe"
            string processName = mck.frpc.Program.frpName;

            // 获取所有匹配的进程
            Process[] processes = Process.GetProcessesByName(processName);

            foreach (Process process in processes)
            {
                try
                {
                    // 确保有足够的权限
                    process.Kill(); // 结束进程
                    process.WaitForExit(); // 等待进程退出
                }
                catch (Exception ex)
                {
                    Console.WriteLine($"无法结束进程: {ex.Message}");
                }
            }
        }

        private void txt_cmd_TextChanged(object sender, EventArgs e)
        {

        }


        private void Form1_FormClosing(object sender, FormClosingEventArgs e)
        {
            // 注意判断关闭事件reason来源于窗体按钮，否则用菜单退出时无法退出!
            if (e.CloseReason == CloseReason.UserClosing)
            {
                //取消"关闭窗口"事件
                e.Cancel = true; // 取消关闭窗体 

                //使关闭时窗口向右下角缩小的效果
                this.WindowState = FormWindowState.Minimized;
                this.frpc_notifyIcon.Visible = true;
                //this.m_cartoonForm.CartoonClose();
                this.Hide();
                return;
            }
        }

       /// <summary>
       /// 彻底关闭
       /// </summary>
       /// <param name="sender"></param>
       /// <param name="e"></param>
        private void toolStrip_tuichu_Click(object sender, EventArgs e)
        {
             CloseProcess();
             System.Environment.Exit(0);
        }

        private void frpc_notifyIcon_DoubleClick(object sender, EventArgs e)
        {
            if (this.Visible)
            {
                this.WindowState = FormWindowState.Minimized;
                this.frpc_notifyIcon.Visible = true;
                this.Hide();
            }
            else
            {
                this.Visible = true;
                this.WindowState = FormWindowState.Normal;
                this.Activate();
            }
        }

        /// <summary>
        /// 设置开机自启
        /// </summary>
        private void SetupAutoStart()
        {
            // 获取应用程序的启动路径
            //string exePath = Application.ExecutablePath;
            //string shortcutPath = Path.Combine(
            //    Environment.GetFolderPath(Environment.SpecialFolder.Startup),
            //    "YourAppName.lnk");

            //// 创建快捷方式
            //WshShell shell = new WshShell();
            //IWshShortcut shortcut = (IWshShortcut)shell.CreateShortcut(shortcutPath);
            //shortcut.TargetPath = exePath;
            //shortcut.Save();

            //MessageBox.Show("设置成功！");
        }
    }
}
